<?php
namespace Home\Controller;

class FoodController extends CommonController{
    
    //饮食列表
    public function index(){
        if($pid = I('request.pid')){
            $this->uid = I('request.pid');
        }else{
            $pid = '';
        }
        $this->assign('pid',$pid);
        
        $p = I('request.p') ? I('request.p') : 1;
        $list = M('Food')->where(array('uid'=>$this->uid))->order('id desc')->page($p.',10')->select();
        if($p == 1){
            $this->assign('list',$list);
            $this->display();
        }else{
            if(empty($list)){
                echo json_encode('err');die;
            }else{
                echo json_encode($list);die;
            }
        }
    }
    
    //记录饮食
    public function edit(){
        $Food = D('Food');
        $create_date = date('Y-m-d');
        if(IS_POST){
            if(I('post.id')){
                $res = $Food->save(array(
                    'id'=>I('post.id'),'uid'=>$this->uid,'name'=>I('post.name'),'des'=>I('post.des'),
                    'create_date'=>I('post.create_date'),'time_section'=>I('post.time_section'),'pic'=>I('post.pic')
                ));
            }else{
                 $res = $Food->add(array(
                    'uid'=>$this->uid,'name'=>I('post.name'),'des'=>I('post.des'),'create_date'=>I('post.create_date'),
                    'time_section'=>I('post.time_section'),'pic'=>I('post.pic')
                ));
            }
            
            D('Score')->addFood($this->uid);//积分-增加
            
            $res ? die('suc') : die('err');
        }else{
            $Resource = D('Resource');
            $this->assign('timeSection',$Resource->getResByType('time_section'));//用餐时间段
            $this->assign('warnFood',$Resource->getResByType('food'));//警示食物
            
            if(I('get.id')){
                $vo = $Food->find(intval(I('get.id')));
                $this->assign('vo',$vo);
                $this->assign('nameArr',explode(',',$vo['name']));//警示食物
                if($vo['pic']) $this->assign('picArr',explode(',',$vo['pic']));//图片数组
            }
			$this->assign('defaultDate',Date('Y-m-d'));
            $this->display();
        }
    }
    
    public function del(){
        $Food = M('Food');
        $id = I('post.id');
        $row = $Food->find($id);
        if($row['uid'] == $this->uid){
            $res = $Food->delete($id);
            $res ? die('suc') : die('err');
        }else{
            die('err');
        }
    }
    
}